package com.project.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @author lyl
 * description:
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService iUserService;

    @RequestMapping("findByPage")
    public PageInfo<UserBean> findByPage(int pageNo) {
        return iUserService.findAllUser(pageNo);
    }

    @RequestMapping("register")
    public String register(@Valid UserBean userBean, BindingResult result) throws JsonProcessingException {
        if (result.hasErrors()) {
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            String errorStr = om.writeValueAsString(errorList);
            return errorStr;
        } else {
            iUserService.register(userBean);
            return "ok";
        }
    }
}
